import { newUuid } from '@/utils'
import { AddSubscription, RemoveSubscription } from '@wails/client/clientfunc'
import { Events } from '@wailsio/runtime';
import { defineStore } from 'pinia'
import { ref } from 'vue'

const Dict = {
  CurrentSummoner: '/lol-summoner/v1/current-summoner', // 当前召唤师消息
  ReadyCheck: '/lol-matchmaking/v1/ready-check', // 是否接受对局
  SearchState: '/lol-lobby/v2/lobby/matchmaking/search-state', // 是否在匹配中
  Gameflow: '/lol-gameflow/v1/session', // 游戏流程
  CurrentMatch: '/lol-champ-select/v1/session', // 当前对局(选择英雄时)
  MatchMembers: '/lol-lobby/v1/lobby/members', // 当前对局成员
}

export const useMessageListStore = defineStore('messageList', () => {
  // 响应式消息列表
  const messageList = ref([])

  // 初始化事件监听
  const init = () => {
    Events.Off('clientConnection')
    Events.On('clientConnection', ({ data }) => {
      try {
        if (data[0] === 'Connected' || data[0] === 'Disconnected') {
          console.log(`ws连接${data[0] === 'Connected' ? '成功' : '断开'}`)
        } else {
          const row = JSON.parse(data[0])[2] || {}
          console.log('收到消息', row);
          const matched = messageList.value.find(item => row.uri === item.url)
          matched.triggers.forEach(({ trigger }) => trigger(row))
        }
      } catch (error) {
        console.log('未定义的回参格式', error)
      }
    })
  }

  // 立即初始化
  init()

  // 添加消息订阅
  const addMessage = ({ name, trigger }) => {
    const url = Dict[name]
    if (!url) {
      console.error('消息名称不存在', name)
      return
    }

    const uuid = newUuid()
    const existing = messageList.value.find(item => item.name === name)

    if (existing) {
      existing.triggers.push({ uuid, trigger })
    } else {
      AddSubscription(url)
      messageList.value.push({
        name,
        url,
        triggers: [{ uuid, trigger }],
      })
    }
    console.log('添加消息成功', name, uuid, messageList.value);
    return uuid
  }

  // 移除消息订阅
  const removeMessage = (name, uuid) => {
    const url = Dict[name]
    if (!url) return

    const index = messageList.value.findIndex(item => item.name === name)
    if (index === -1) return

    const triggers = messageList.value[index].triggers
    const triggerIndex = triggers.findIndex(t => t.uuid === uuid)
    if (triggerIndex === -1) return

    triggers.splice(triggerIndex, 1)
    if (triggers.length === 0) {
      RemoveSubscription(url)
      messageList.value.splice(index, 1)
    }
    console.log('移除消息成功', name, uuid)
  }

  return {
    messageList,
    addMessage,
    removeMessage,
  }
})
